﻿using System; 
using System.Data;
using System.Collections.Generic; 
using JOIN.Rights.Model;
using Kevin.Framework;
using Kevin.Framework.Data;
using System.Diagnostics;
using log4net;

/*------------------------------------------------------------------------
   苏州捷安信息科技有限公司 版权所有			
   文件名: TU_User.cs
   作 者 : 席吉波
   日 期 : 2012-10-19
   备 注 : 当您对本文件更改时请写明修改人、修改日期以及事由
  ------------------------------------------------------------------------
*/

namespace JOIN.Rights.BLL
{
	 	//TU_User
		/// <summary>
	/// User 业务操作类
	/// </summary>
	public partial class UserBLL:BLLBase<UserInfo>,ISelect<UserInfo>
	{
        private static readonly ILog logger = LogManager.GetLogger(typeof(UserBLL));
        System.Diagnostics.Stopwatch watch1 = new Stopwatch();

		#region   构造函数
		
		/// <summary>
		/// UserBLL  构造函数  
		/// </summary>
		public UserBLL(UserInfo entity)
			:base(entity)
		{
		
		}
		/// <summary>
		/// UserBLL  构造函数  
		/// </summary>
		/// <param name="operationMode">操作模式</param>
        /// <param name="jsonEntity">前台javascript传过来的JSON实体</param>
		public UserBLL(string operationMode, string jsonEntity)
        {
            OperState cmd = (OperState)Enum.Parse(typeof(OperState), operationMode);
            UserInfo entity = ConvertJSON2Entity(jsonEntity);
            base.OperState = cmd;
            base.Entity = entity;
            base.ServiceResult = new ServiceResult<UserInfo>();
            base.ServiceResult.Successed = true;
            base.ServiceResult.Object = base.Entity;
        }
        
        #endregion
        
        #region 查询方法
        
        /// <summary>
        /// 获取 UserInfo 集合
        /// </summary>
        /// <param name="pageSize">分页记录数</param>
        /// <param name="pageIndex">页码索引</param>
        /// <returns></returns>
        public ServiceResult<UserInfo> SelectByProperties(int pageSize, int pageIndex)
        {
            this.ServiceResult = new ServiceResult<UserInfo>();
            try
            {
                int recordCount =0;
                List<UserInfo> list = base.Entity.SelectedByProperties<UserInfo>(out recordCount,pageSize,pageIndex);
                
                ServiceResult.Successed = true;
                ServiceResult.RecordCount = recordCount;
                ServiceResult.List = list;
                
            }
            catch(Exception ex){
                ServiceResult.ErrorMsg = "数据查询失败:"+ex.Message;
                ServiceResult.Successed = false;
                ServiceResult.RecordCount = 0;
                ServiceResult.List = null;
            }

            return ServiceResult;
        }

        public ServiceResult<UserInfo> SelectByRoleID(int pageSize, int pageIndex)
        {
            this.ServiceResult = new ServiceResult<UserInfo>();
            try
            {
                int recordCount = 0;
                List<UserInfo> list = base.Entity.SelectedByProperties<UserInfo>(out recordCount, pageSize, pageIndex);

                ServiceResult.Successed = true;
                ServiceResult.RecordCount = recordCount;
                ServiceResult.List = list;

            }
            catch (Exception ex)
            {
                ServiceResult.ErrorMsg = "数据查询失败:" + ex.Message;
                ServiceResult.Successed = false;
                ServiceResult.RecordCount = 0;
                ServiceResult.List = null;
            }

            return ServiceResult;
        }

        /// <summary>
        /// 用户校验，校验通过的话会返回一个会话ID及其他信息
        /// </summary>
        /// <returns></returns>
        public ServiceResult<OnlineUserInfo> Check(string projectID="")
        {
            watch1.Start();
            ServiceResult<OnlineUserInfo>  serviceResult = new ServiceResult<OnlineUserInfo>();
            try
            {
                int recordCount = 0;
                List<UserInfo> list = base.Entity.SelectedByProperties<UserInfo>(out recordCount, 1, 1);

                serviceResult.Successed = list.Count > 0;

                if (serviceResult.Successed)
                {
                    OnlineUserInfo user = new OnlineUserInfo();
                    user.UserNO = base.Entity.UserNO;
                    user.UserName = base.Entity.UserName;
                    user.LoginTime = DateTime.Now;
                    user.TokenID = Guid.NewGuid().ToString();
                    user.UserEntity = list[0];
                    user.CompanyEntity = new CompanyInfo() { CompanyID = user.UserEntity.CompanyID }.SelectedByProperties<CompanyInfo>()[0];
                    
                    user.ProjectID = projectID;
                    
                    user.Insert();
                    serviceResult.Object = user;
                    serviceResult.RecordCount = recordCount;
                    serviceResult.List = null;
                }
                else
                {
                    serviceResult.ErrorMsg = "用户验证失败，请输入正确的帐号密码！";
                }
            }
            catch (Exception ex)
            {
                serviceResult.ErrorMsg = "登录失败:" + ex.Message;
                serviceResult.Successed = false;
                serviceResult.RecordCount = 0;
                serviceResult.List = null;
            }
            watch1.Stop();
            logger.Info(string.Format("user check:",watch1.Elapsed));
            return serviceResult;
        }

        public ServiceResult<UserInfo> ChangePassword(string userNO, string oldPwd, string newPwd)
        {
            ServiceResult<UserInfo> result = new ServiceResult<UserInfo>();

            UserInfo user = new UserInfo() { UserNO = userNO, UserPwd = oldPwd.ToMD5String() };
            
            if (!user.SelectedSingleByProperties())
            {
                result.Successed = false;
                result.ErrorMsg = "旧密码不正确！";
            }
            else
            {
                user.UserPwd = newPwd.ToMD5String();
                user.Update();
                result.Successed = true;
            }
            return result;
        }
        #endregion
        
        #region 重写基类方法

        protected override bool PreSaveProcess()
        {
            if (this.OperState == BLL.OperState.Add)
            {
                UserInfo user = new UserInfo();
                user.UserNO = this.Entity.UserNO;
                if (user.SelectedByProperties().Rows.Count > 0)
                {
                    this.ServiceResult = new ServiceResult<UserInfo>();
                    ServiceResult.Successed = false;
                    ServiceResult.ErrorMsg = "用户：" + Entity.UserNO + " 已经存在！";
                    ServiceResult.Object = this.Entity;
                    return false;
                }
                this.Entity.UserPwd = this.Entity.UserPwd.ToMD5String();
            }
            
            
            return true;
        }

        protected override void AfterSaveProcess()
        {
            UserRoleInfo uri = new UserRoleInfo();
            uri.UserID = base.Entity.UserID.ToString();
            //uri.RoleID = string.IsNullOrEmpty(base.Entity.RoleID) ? "0" : base.Entity.RoleID;
            string roleID = string.IsNullOrEmpty(base.Entity.RoleID) ? "0" : base.Entity.RoleID;
            if (this.OperState == BLL.OperState.Add)
            {
                //uri.Insert();
                InsertRoles(uri.UserID, roleID);
            }
            else
            {
                uri.Delete(false);
                InsertRoles(uri.UserID, roleID);
            }
        }

        private void InsertRoles(string userID,string roles)
        {
            string[] roleArray = roles.Split(',');
            foreach (string role in roleArray)
            {
                UserRoleInfo uri = new UserRoleInfo();
                uri.UserID = userID;
                uri.RoleID = role;
                uri.Insert();
            }
        }


        protected override bool AfterDelete()
        {
            UserRoleInfo uri = new UserRoleInfo();
            uri.UserID = base.Entity.UserID.ToString();
            uri.Delete();
            return true;
        }
        #endregion
   
	}
}